package com.ruoyi.auth.controller;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.RandomUtil;
import com.ruoyi.system.api.model .LoginDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;

import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    private static final Logger log = LoggerFactory.getLogger(TokenController.class);
    
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;






    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }
    
    @PostMapping("driverLogin")
    public R<?> driverLogin(@RequestBody LoginDriver loginDriver)
    {
        try {
            // 用户登录
            R<LoginUser> loginResult = sysLoginService.driverLogin(loginDriver.getPhonenumber(), loginDriver.getCode());
            if (R.isSuccess(loginResult)) {
                // 获取登录用户信息
                LoginUser loginUser = loginResult.getData();
                if (loginUser == null || loginUser.getSysUser() == null) {
                    return R.fail("用户信息不完整，无法创建令牌");
                }
                // 创建token
                return R.ok(tokenService.createToken(loginUser));
            }
            return loginResult;
        } catch (Exception e) {
            log.error("司机登录失败: {}", e.getMessage());
            return R.fail("登录失败，请稍后重试");
        }
    }

    @GetMapping("sendCode/{phonenumber}")
    public R<?> sendCode(@PathVariable("phonenumber") String phonenumber)
    {
        try {
            String code = RandomUtil.randomNumbers(4);
            
            // 存储验证码到Redis
            stringRedisTemplate.opsForValue().set("mobile" + phonenumber, code, 5, TimeUnit.MINUTES);
            log.info("验证码已生成并存储: 手机号 {}, 验证码: {}", phonenumber, code);
            
            // 返回验证码，前端将通过弹窗显示
            return R.ok(code, "验证码：" + code);
        } catch (Exception e) {
            log.error("生成验证码异常: 手机号 {}, 错误信息: {}", phonenumber, e.getMessage());
            return R.fail("系统异常，请稍后重试");
        }
    }




    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }



    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}